import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.HashMap;
import java.util.Scanner;

import stub.Product;


public class Server{
	
	public static void main( String args[] ) {
		
		try{
			// Create a new instance of the warehouse implementation
			WarehouseImpl warehouse = new WarehouseImpl();
			
			// Create registry with port 1099
			Thread registryThread = new Thread(){
				
				public void run() {
					try{
						LocateRegistry.createRegistry( 1099 );
					} catch( RemoteException e ){
						e.printStackTrace();
					}
				}
			};
			registryThread.start();
			
			// Bind the remote object's stub in the registry
			Registry registry = LocateRegistry.getRegistry();
			registry.bind( "Warehouse", warehouse );
			
			System.err.println( "Server ready" );
			
			// Admin functionality
			Scanner scanner = new Scanner( System.in );
			while( true ){
				System.out.println( "Admin scherm" );
				System.out.println( "[1] Toon alle orders" );
				
				int selection = scanner.nextInt();
				
				if( selection == 1 ){
					HashMap<Integer, Order> orders = warehouse.getOrders();
					int counter = 0;
					for( Integer orderId : orders.keySet() ){
						Order order = orders.get( orderId );
						System.out.println("\n\n");
						if(counter == 0){
							System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
							System.out.println("---------------------");
							counter++;
						}
						System.out.println("Order nummer: " + orderId);
						System.out.println("Klant: " + order.getCustomerName() );
						System.out.println("\nProducts:");
						
						if(order.getProductsOverview().size() > 0){
							System.out.println(String.format( "%-25s %-5s %5s", "naam", "prijs", "aantal" ));
						}
						for( Product p : order.getProductsOverview().keySet() ){
							System.out.println(String.format( "%-25s %-5s %5s", p.getName() , p.getPrice() , order.getProductsOverview().get( p ) ));
						}
						

						System.out.printf("Order totaal:   %.2f", order.getTotalPrice() );
						System.out.println("\nOrder besteld:  " + order.secured());
						System.out.println("---------------------");
					}
				}
				System.out.println("\n\n");
			}
			
		} catch( Exception e ){
			System.err.println( "Server exception: " + e.toString() );
			e.printStackTrace();
		}
	}
	
}